package com.haredot.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.haredot.entity.Notify;
import com.haredot.holder.TokenContextHolder;
import com.haredot.mapper.NotifyMapper;
import com.haredot.service.NotifyService;
import com.haredot.vo.R;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Transactional(rollbackFor = Exception.class)
public class NotifyServiceImpl extends ServiceImpl<NotifyMapper, Notify> implements NotifyService {

    @Override
    public R<Map<String, Long>> queryUnReadMessages() {
        // 获取当前登录的用户 ID
        Long userId = TokenContextHolder.getCurrentUserId() ;
        // 查询 公告 未读数量
        Long officialNum = 0L ;

        // 查询 通知未读数量
        Long notifyNum = this.getBaseMapper().selectCount(new LambdaQueryWrapper<Notify>()
                .eq(Notify::getUserId, userId)
                .eq(Notify::isNread, false));

        // 查询私信未读数量
        Long letterNum = this.getBaseMapper().findLetterUnReadCount(userId) ;

        Map<String, Long> mapCount = Map.of("official", officialNum, "notify", notifyNum, "letter", letterNum);

        return R.<Map<String, Long>>ok().data(mapCount);
    }

    @Override
    public R<Page<Notify>> queryNotifys(Page<Notify> page) {

        Long currentUserId = TokenContextHolder.getCurrentUserId();

        Page<Notify> notifyPage = this.getBaseMapper()
                .selectPage(page, new LambdaQueryWrapper<Notify>()
                        .eq(Notify::getUserId, currentUserId)
                        .orderByDesc(Notify::getId));

        // 获取查询到的记录、并将信息设置为已读
        List<Notify> records = notifyPage.getRecords();

        // 获取当前页所有通知ID
        List<Long> collect = records.stream().filter(notify -> !notify.isNread())
                .map(notify -> notify.getId()).collect(Collectors.toList());

        if (!collect.isEmpty()) {
            // 批量更新数据状态为 已读
            this.getBaseMapper().batchUpdateReadState(collect);
        }
        return R.<Page<Notify>>ok().data(notifyPage);
    }
}
